<template>
  <el-dialog :close-on-click-modal="false" v-model="visible" title="表结构配置" @close="resetForm" width="80%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-row>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="targetType" label="目标端类型">
                <!-- <el-input v-model="formData.targetType" placeholder="请输入副本数" /> -->
                <el-select @change="handleTypeChange" v-model="formData.targetType" placeholder="请选择目标端类型" filterable clearable>
                  <el-option v-for="(item) in dbTypeList"
                    :key="item.dictLabel"
                    :label="item.dictLabel"
                    :value="item.dictLabel"
                   />
                  </el-select>
              </el-form-item>

              <el-form-item v-if="formData.targetType == 'Doris' || formData.targetType == 'ElasticSearch'" prop="replicationAllocation" label="副本数">
                <el-input v-model="formData.replicationAllocation" placeholder="请输入副本数" />
              </el-form-item>

              <el-form-item v-if="formData.targetType == 'ElasticSearch'" prop="shards" label="分片数">
                <el-input v-model="formData.shards" placeholder="请输入分片数" />
              </el-form-item>

              <el-form-item v-if="formData.targetType == 'ClickHouse'" prop="engine" label="引擎">
                <!-- <el-input v-model="formData.targetType" placeholder="请输入副本数" /> -->
                <el-select v-model="formData.engine" placeholder="请选择引擎" filterable clearable>
                  <el-option v-for="(item) in engineList"
                    :key="item.dict_value"
                    :label="item.dict_label"
                    :value="item.dict_value"
                   />
                  </el-select>
              </el-form-item>

            </el-col>
          </el-row>
        </el-col>
        <el-col :span="11">
          <div class="tree"
          v-loading="tableLoading"
          >
            <el-tree
              ref="treeRef"
              :data="tableList"
              :props="{ label: 'name' }"
              node-key="value"
              default-expand-all
              :expand-on-click-node="false"
              show-checkbox
              :highlight-current="false"
            ></el-tree>
          </div>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="getSql">
            确定
            <el-icon class="el-icon--right"><Right /></el-icon>
          </el-button>
        </el-col>
        <el-col :span="11">
          <div style="height: 400px;overflow: auto;" v-loading="codeLoading">
            <template v-for="(item,index) in tableSqls" :key="index">
              <!-- <p class="tableName">{{item.table}}</p> -->
              <el-input v-model="item.table" ></el-input>
            <codemirror
              v-model="item.sql"
              placeholder="Coding..."
              :style="{ height: '300px' }"
              :autofocus="true"
              :tabSize="2"
              :extensions="extensions"
            />
            </template>

          </div>
        </el-col>
        <el-col :span="12" class="mt-2">
          <el-form-item prop="targetId" label="目标数据库">
            <el-select v-model="formData.targetId" placeholder="请选择目标数据库" filterable clearable>
              <el-option v-for="item in targetSourceList" :key="item._id" :label="item.datasourceName" :value="item._id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="handleCreate">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch } from 'vue-demi'
import {
  createsStarrocktsProperties,
  findStarrocktsProperties,
  findTableName,
  batchCreateDorisSql,
  batchCreateDorisTable,
  getCkEngine,
  batchCreateTable,
  batchExecTableSql
} from '@/api/datasourceCenter'
import { Codemirror } from 'vue-codemirror'
import { xml } from '@codemirror/lang-xml'
import { sql } from '@codemirror/lang-sql'
import { oneDark } from '@codemirror/theme-one-dark'
import { EditorView } from '@codemirror/view'
import { Right } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { json } from '@codemirror/lang-json'



const code = ref('')
const extensions = [sql(), oneDark]

const tableLoading = ref(false)

const props = defineProps({
  datasource: {
    type: Object,
    default: () => {}
  },
  visible: {
    type: Boolean,
    default: false
  },
  datasourceList: {
    type: Array,
    default: () => []
  },
  dbTypeList: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['update:visible', 'create', 'update'])

const engineList = ref([])


const formRef = ref()
const submitBtnLoading = ref(false)
const codeLoading = ref(false)
const formData = reactive({
  replicationAllocation: '',
  targetId: '',
  engine: '',
  shards: '',
})

const formRules = reactive({
  replicationAllocation: [{ required: true, trigger: 'blur', message: '请输入副本数！' }],
  targetId: [{ required: true, trigger: 'blur', message: '目标数据库！' }],
  engine: [{ required: true, trigger: 'blur', message: '请选择引擎！' }],
  shards: [{ required: true, trigger: 'blur', message: '请输入分片数！' }],
})
const tableList = ref([])
const tableSqls = ref([])
const treeRef = ref(null)
const targetSourceList = ref([])
const resetForm = () => {
  formRef.value?.resetFields()
  emit('update:visible')
  tableList.value = []
  tableSqls.value = []
}

const handleTypeChange = (val)=>{
  console.log(val)

  formData.targetId = ''

  //从datasourceList中筛选所有type为val的数据源
  targetSourceList.value = props.datasourceList.filter(item => item.type == val) || []


}

const handleCreate = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      const params = {
        targetId: formData.targetId,
        sqls: tableSqls.value
      }
      submitBtnLoading.value = true
      batchExecTableSql(params)
        .then((res) => {
          ElMessage.success(res.data)
          resetForm()
        })
        .finally(() => {
          submitBtnLoading.value = false
        })
    }
  })
}
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // console.log(props.datasource)
      console.log('props.datasourceList')

      console.log(props.datasourceList)

      console.log('props.dbTypeList')

      console.log(props.dbTypeList)

      getCkEngine().then((res) => {
        engineList.value = res.data
      })

      // findStarrocktsProperties(props.datasource._id).then((res) => {
      //   if (res.data) {
      //     Object.assign(formData, res.data)
      //     handleCreate()
      //   }
      // })
      tableLoading.value = true
      findTableName(props.datasource).then((res) => {
        tableList.value = [
          {
            name: '表',
            value: 'table',
            children: res.data.map((item) => {
              return {
                name: item,
                value: item
              }
            })
          }
        ]
      })
      .finally(()=>{
        tableLoading.value = false
      })
    } else {
      code.value = ''
    }
  }
)
const getSql = () => {
  const checked = treeRef.value.getCheckedKeys(true)
  if (checked.length === 0) {
    ElMessage.warning('请选择表')
    return
  }
  if (formData.targetType === '') {
    ElMessage.warning('请输入副本数')
    return
  }
  if (formData.replicationAllocation === '' && (formData.targetType == 'Doris' || formData.targetType == 'ElasticSearch')) {
    ElMessage.warning('请输入副本数')
    return
  }

  if ((formData.engine === '' || formData.targetId === '') && formData.targetType == 'ClickHouse') {
    ElMessage.warning('请选择引擎和目标端')
    return
  }

  if (formData.shards === '' && formData.targetType == 'ElasticSearch') {
    ElMessage.warning('请输入分片数')
    return
  }

  //如果不是Doris或ElasticSearch，replicationAllocation置空
  if(formData.targetType != 'Doris' && formData.targetType != 'ElasticSearch'){
    formData.replicationAllocation = ''
  }

  //如果不是ClickHouse，engine置空
  if(formData.targetType != 'ClickHouse'){
    formData.engine = ''
  }

  //如果不是ElasticSearch，shards置空
  if(formData.targetType != 'ElasticSearch'){
    formData.shards = ''
  }

  const params = {
    sourceId: props.datasource._id,
    tableName: checked,
    targetType: formData.targetType,
    replicationAllocation: formData.replicationAllocation || '',
    engine: formData.engine || '',
    shards: formData.shards || '',
    targetId: formData.targetId || ''
  }
  codeLoading.value = true
  batchCreateTable(params)
    .then((res) => {
      let data = res.data
      if(params.targetType == 'ElasticSearch'){

        // 遍历data，将每个表的sql转为json格式
        data.forEach((item) => {
          item.sql = JSON.stringify(JSON.parse(item.sql), null, '\t')
        })

      }
      tableSqls.value = ''
      code.value = ''

      tableSqls.value = data

//       data.forEach((item) => {
//         code.value += `-- ${item.table}
//       ${item.sql}

// `
//       })
    })
    .finally(() => {
      codeLoading.value = false
    })
}
</script>

<style lang="scss" scoped>
.tree {
  height: 400px;
  overflow: auto;
}
.tableName{
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

</style>

<style>

.el-message__content{
  white-space: pre-wrap;
}
</style>
